package com.admin.service.impl;

import com.admin.entity.Admin;
import com.admin.entity.Apk;
import com.admin.entity.Theme;
import com.admin.mapper.AdminMapper;
import com.admin.mapper.ApkMapper;
import com.admin.mapper.ThemeMapper;
import com.admin.service.IApkService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@SuppressWarnings("ALL")
@Service
public class ApkServiceImpl extends ServiceImpl<ApkMapper, Apk> implements IApkService {


    @Autowired
    private ApkMapper apkMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private ThemeMapper themeMapper;

    /**
     * 查询普通Apk 以及根据条件查询
     *
     * @param page
     * @param limit
     * @param id
     * @param map
     * @return
     */
    public IPage searchApkWithPageById(int page, int limit, int id, Map map) {
        Page p = new Page(page, limit);
        IPage iPage = apkMapper.searchApkWithPageById(p, id, map);
        return iPage;
    }


    /**
     * 新增普通apk应用
     *
     * @param apk
     * @param username
     * @return
     */
    public int addApk(Apk apk, String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_phone", username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin != null) {
            apk.setApkAdmin(admin.getAdminId());
           /* if(selectApkMd5AndApkAdmin(apk.getApkMd5(),apk.getApkAdmin())!=null){
                return 0;
            }*/
        } else {
            return 0;
        }
        int insert = apkMapper.insert(apk);
        return insert;
    }

    /**
     * 查询普通apk根据用户，Md5进行比较
     *
     * @param apkMd5
     * @param apkAdmin
     * @return
     */
    public Apk selectApkMd5AndApkAdmin(String apkMd5, int apkAdmin) {
        QueryWrapper q = new QueryWrapper();
        q.eq("apk_md5", apkMd5);
        q.eq("apk_admin", apkAdmin);
        Apk apk = apkMapper.selectOne(q);
        return apk;
    }

    /**
     * 查所有未审核apk
     *
     * @param page
     * @param limit
     * @param admin
     * @return
     */
    @Override
    public IPage apkShenhe(int page, int limit, Admin admin) {
        Page p = new Page(page, limit);
        String adminids = adminMapper.getAllChildUser(admin.getAdminId());
        List adminidlist= Arrays.asList(adminids.split(","));

        IPage re = apkMapper.apkshenhe(p,adminidlist);
        return re;
    }

    /**
     * apk未审核的数量
     *
     * @return
     */
    @Override
    public int apkWeishenheCount() {
        QueryWrapper q = new QueryWrapper();
        q.eq("apk_shenhe", "未审核");
        int count = apkMapper.selectCount(q);
        return count;
    }

    public Admin findAdminByPhone(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_phone", username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    /**
     * 更新所有站点某个apk
     *
     * @param apk
     * @return
     */
    @Override
    public boolean updateAllStationByApk(Apk apk) {
        List<Theme> list = themeMapper.selectList(null);
        for (Theme t : list) {
            //更新已生效桌面配置
            String senxiao_pc = t.getThemeAuditPcAudited();
            String senXiao_pc_new = processSenxiaoPc(apk, senxiao_pc);
            if (senXiao_pc_new != null) {
                t.setThemeAuditPcAudited(senXiao_pc_new);
                themeMapper.updateById(t);
            }
            //更新未生效桌面配置
            String nosenxiao_pc = t.getThemeAuditPcUnaudited();
            String nosenxiao_pc_new = processSenxiaoPc(apk, nosenxiao_pc);
            if (nosenxiao_pc_new != null) {
                t.setThemeAuditPcUnaudited(nosenxiao_pc_new);
            }

            //更新已生效android
            String shenxiao_android = t.getThemeAuditAndroidAudited();
            String shenxiao_android_new = processSenxiaoAndroid(apk, shenxiao_android);
            if (shenxiao_android_new!=null){
                t.setThemeAuditAndroidAudited(shenxiao_android_new);
            }

            //更新已生效android
            String shenxiao_android_en = t.getEnglishAndroidYes();
            String shenxiao_android_new_en = processSenxiaoAndroidEnglish(apk, shenxiao_android_en);
            if (shenxiao_android_new_en!=null){
                t.setEnglishAndroidYes(shenxiao_android_new_en);
            }


            //更新未生效android
            String no_sehenxiao_android = t.getThemeAuditAndroidUnaudited();
            String no_sehenxiao_android_new = processSenxiaoAndroid(apk,no_sehenxiao_android);
            if (no_sehenxiao_android_new!=null){
                t.setThemeAuditAndroidUnaudited(no_sehenxiao_android_new);
            }

            themeMapper.updateById(t);

        }
        return true;
    }

    /**
     * 更新主题中生效的安卓
     *
     * @param apk
     * @param shenxiao_android
     * @return
     */
    private String processSenxiaoAndroid(Apk apk, String shenxiao_android) {
        if (apk == null || shenxiao_android == null || shenxiao_android.trim().length() == 0) {
            return null;
        }
       JSONArray  data = null;
        JSONObject rootObject = null;
        try {
            rootObject = JSONObject.parseObject(shenxiao_android);
            data = rootObject.getJSONObject("data").getJSONObject("CN").getJSONObject("desktop").getJSONObject("main").getJSONArray("data");
        } catch (Exception e) {
            return null;
        }
        if (data == null || data.size()==0) {
            return null;
        }

        for (int i=0;i<data.size();i++){
            JSONObject  content =  data.getJSONObject(i).getJSONObject("content");
            if (content==null){
                continue;
            }

            JSONArray info  = content.getJSONArray("info");
            if (info==null || info.size()==0){
                continue;
            }

            for (int j=0;j<info.size();j++){
                JSONObject infoObject = info.getJSONObject(j);
                String packageName = infoObject.getString("packageName");
                String apkUrl = infoObject.getString("apk");
                if (apk.getApkPackage().equals(packageName)) {
                    infoObject.put("apk", apk.getApkUrl() + "?md5=" + apk.getApkMd5());
                }
            }



        }



        return rootObject.toJSONString();

    }


    /**
     * 更新主题中生效的安卓(英)
     *
     * @param apk
     * @param shenxiao_android
     * @return
     */
    private String processSenxiaoAndroidEnglish(Apk apk, String shenxiao_android) {
        if (apk == null || shenxiao_android == null || shenxiao_android.trim().length() == 0) {
            return null;
        }
        JSONArray  data = null;
        JSONObject rootObject = null;
        try {
            rootObject = JSONObject.parseObject(shenxiao_android);
            data = rootObject.getJSONObject("data").getJSONObject("EN").getJSONObject("desktop").getJSONObject("main").getJSONArray("data");
        } catch (Exception e) {
            return null;
        }
        if (data == null || data.size()==0) {
            return null;
        }

        for (int i=0;i<data.size();i++){
            JSONObject  content =  data.getJSONObject(i).getJSONObject("content");
            if (content==null){
                continue;
            }

            JSONArray info  = content.getJSONArray("info");
            if (info==null || info.size()==0){
                continue;
            }

            for (int j=0;j<info.size();j++){
                JSONObject infoObject = info.getJSONObject(j);
                String packageName = infoObject.getString("packageName");
                String apkUrl = infoObject.getString("apk");
                if (apk.getApkPackage().equals(packageName)) {
                    infoObject.put("apk", apk.getApkUrl() + "?md5=" + apk.getApkMd5());

                }
            }



        }



        return rootObject.toJSONString();

    }

    /**
     * 更新主题中所有生效的apk
     *
     * @param senxiao_pc
     */
    private String processSenxiaoPc(Apk apk, String senxiao_pc) {
        if (apk == null || StringUtil.isNull(apk.getApkUrl()) || StringUtil.isNull(apk.getApkPackage())) {
            return null;
        }
        if (StringUtil.isNull(senxiao_pc)) {
            return null;
        }

        if (senxiao_pc.startsWith("fun_id('") == false) {
            return null;
        }

        String tempStr = senxiao_pc.substring(8, senxiao_pc.length() - 2);
        JSONObject rootJson = JSONObject.parseObject(tempStr);
        JSONObject pannelObject = rootJson.getJSONObject("panel");
        if (pannelObject == null) {
            return null;
        }

        JSONObject mainObject = pannelObject.getJSONObject("MAIN");
        if (mainObject == null) {
            return null;
        }

        JSONArray dataArray = mainObject.getJSONArray("data");
        if (dataArray == null || dataArray.size() == 0) {
            return null;
        }

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject itemObject = dataArray.getJSONObject(i);
            if (itemObject == null) {
                continue;
            }
            JSONObject dataObject = itemObject.getJSONObject("data");
            if (dataObject == null) {
                continue;
            }
            JSONArray infoArray = dataObject.getJSONArray("info");
            if (infoArray == null || infoArray.size() == 0) {
                return null;
            }
            for (int j = 0; j < infoArray.size(); j++) {
                JSONObject infoObject = infoArray.getJSONObject(j);
                if (infoObject == null) {
                    continue;
                }
                String packageName = infoObject.getString("packageName");
                String apkUrl = infoObject.getString("apk");
                if (apk.getApkPackage().equals(packageName)) {
                    infoObject.put("apk", apk.getApkUrl() + "?md5=" + apk.getApkMd5());
                }
            }

        }
        String json = rootJson.toJSONString();
        return "fun_id('" + json + "')";
    }





}
